<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        div {
            width: 100px;
            height: 100px;
            background-color: blueviolet;
            position: absolute;
        }
    </style>
</head>

<body>
    <div></div>
</body>
<script>
    let div = document.querySelector('div');

    let isok = false;
    div.onmousedown = () => isok = true;
    div.onmouseup = () => isok = false;

    window.onmousemove = e => {
        if (isok) {
            e = e || window.event;
            let eleX = e.clientX - div.offsetWidth / 2;
            let eleY = e.clientY - div.offsetHeight / 2;

            if (eleX >= window.innerWidth - div.offsetWidth) {
                eleX = window.innerWidth - div.offsetWidth;
            } else if (eleX < 0) {
                eleX = 0;
            }

            if (eleY >= window.innerHeight - div.offsetHeight) {
                eleY = window.innerHeight - div.offsetHeight;
            } else if (eleY < 0) {
                eleY = 0;
            }

            div.style.left = eleX + 'px';
            div.style.top = eleY + 'px';
        }
    }
</script>

</html>